package com.wh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wh.beans.ConstVar;
import com.wh.beans.ValueText;
import com.wh.dao.BaseDao;
import com.wh.dao.ext.SysEnumDao;
import com.wh.dao.ext.SysEnumNameDao;
import com.wh.model.BaseModel;
import com.wh.model.SysEnum;
import com.wh.model.SysEnumName;
import com.wh.service.IExt.ISysEnumNameService;
import com.legend.utils.*;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SysEnumNameService extends BaseServiceImp implements ISysEnumNameService {
    Logger log = Logger.getRootLogger();
    private SysEnumNameService() {
    }

    //volatile修饰的写变量不能和之前的读写代码调整，读变量不能和之后的读写代码调整
    private volatile static ISysEnumNameService instance = null;

    /**
     * 单例
     *
     * @return
     */
    public static ISysEnumNameService getInstance() {
        if (instance == null) {
            synchronized (ISysEnumNameService.class) {
                if (instance == null) {
                    instance = new SysEnumNameService();
                }
            }
        }
        return instance;
    }
    public ReturnResult delByIds(String ids) {
        SqlSession session = getSqlSession();
        ReturnResult result = new ReturnResult();
        try {
            SysEnumNameDao dao = session.getMapper(SysEnumNameDao.class);
            result = delByMap(dao, ids);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            result.setMsg(i18nUtils.getVal("100002000"));
        } finally {
            session.close();
        }
        return result;
    }

    /**
     * 分页数据查询
     *
     * @param pageIndex
     * @param pageSize
     * @param map
     * @return
     */
    public ReturnResult selectByMap(int pageIndex, int pageSize, Map<String, Object> map) {
        SqlSession session = getSqlSession();
        SysEnumNameDao dao = session.getMapper(SysEnumNameDao.class);
        int recordNum = (pageIndex - 1) * pageSize;
        List<SysEnumName> lst = session.selectList(ConfigUtils.getInstance().getDaoPackage(".SysEnumNameDao.selectByMap"), map, new RowBounds(recordNum, pageSize));
        int total = dao.count(map);
        ReturnResult result = new ReturnResult();
        result.setMsg(i18nUtils.getVal("100001000"));
        result.setRows(lst);
        result.setTotal(total);
        result.setStatus(Status.SUCCESS);
        session.close();
        return result;
    }

    @Override
    public ReturnResult insertByModel(BaseModel model) {
        SqlSession session = getSqlSession();
        SysEnumNameDao dao = session.getMapper(SysEnumNameDao.class);
        ReturnResult result = insertByModel(dao, model);
        session.close();
        return result;
    }

    @Override
    public ReturnResult editByModel(BaseModel model) {
        SqlSession session = getSqlSession();
        SysEnumNameDao dao = session.getMapper(SysEnumNameDao.class);
        ReturnResult result = editByModel(dao, model);
        session.close();
        return result;
    }

    /**
     * 返回枚举名称列表
     *
     * @param entity
     * @return
     */
    public List<SysEnumName> getEnumNameList(SysEnumName entity) {
        SqlSession session = getSqlSession();
        SysEnumNameDao keyDao = session.getMapper(SysEnumNameDao.class);
        List<SysEnumName> keyLst = keyDao.selectByModel(entity);
        session.close();
        return keyLst;
    }

    /**
     * 更新枚举字典缓存
     */
    public Map<String, Object> setEnumCache() {
        SqlSession session = getSqlSession();
        SysEnumNameDao keyDao = session.getMapper(SysEnumNameDao.class);
        SysEnumName keyEntity = new SysEnumName();
        keyEntity.setStatus(1);
        List<SysEnumName> keyLst = keyDao.selectByModel(keyEntity);
        SysEnumDao valuesDao = session.getMapper(SysEnumDao.class);
        SysEnum valuesEnitty = new SysEnum();
        valuesEnitty.setStatus(1);
        List<SysEnum> valuesLst = valuesDao.selectByModel(valuesEnitty);
        Map<String, Object> map = new HashMap<String, Object>();
        for (SysEnumName en : keyLst) {
            @SuppressWarnings("rawtypes")
            List<ValueText> lstTmp = new ArrayList<ValueText>();
            for (SysEnum ed : valuesLst) {
                if (en.getEnumName().equals(ed.getEnumName())) {
                    ValueText vt = new ValueText();
                    vt.setText(ed.getEnumText());
                    vt.setValue(ed.getEnumValue());
                    lstTmp.add(vt);
                }
            }
            map.put(en.getEnumName(), lstTmp);
        }
        EhCacheUtil.getInstance().put(ConstVar.FEREVER_CACHE, ConstVar.SYSDICTIONARY_CACHE, map);

        session.close();
        return map;
    }

    /**
     * 把枚举缓存内容写到文件中
     * @param map
     * @param request
     */
    public ReturnResult writeEnumFile(Map<String, Object> map, HttpServletRequest request) {

        String filePath = request.getSession().getServletContext().getRealPath("/skins/js/cache");
        ReturnResult result=new ReturnResult();
        try {
            FileUtils.writeFile(filePath + "/enum.js", "var Enum=" +
                    JSONObject.toJSONString(map));
            result.setStatus(Status.SUCCESS);
            result.setMsg(i18nUtils.getVal("100001000"));
        } catch (FileNotFoundException e) {
            log.error("写文件出错:" + e.getMessage());
            result.setData(e.getMessage());

        } catch (UnsupportedEncodingException e) {
            log.error("写文件出错:" +
                    e.getMessage());
            result.setData(e.getMessage());
        }
return result;
    }

    /**
     * 获取指定信息
     *
     * @param mapKey
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<ValueText> getEnumCache(String mapKey) {
        Object object = EhCacheUtil.getInstance().get(ConstVar.FEREVER_CACHE, ConstVar.SYSDICTIONARY_CACHE);
        Map<String, Object> map = new HashMap<String, Object>();
        if (object == null) {
            map = setEnumCache();
        } else {
            map = (Map<String, Object>) object;
        }
        List<ValueText> lst = new ArrayList<ValueText>();
        if (map.containsKey(mapKey)) {
            lst = (List<ValueText>) map.get(mapKey);
        }
        return lst;
    }

    /**
     * 根据ID获取一条数据
     *
     * @param id
     * @return
     */
    public ReturnResult selectById(String id) {
        SqlSession session = getSqlSession();
        ReturnResult result = new ReturnResult();
        result.setStatus(Status.ERROR);
        BaseDao dao = session.getMapper(SysEnumNameDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        List<SysEnumName> lst = dao.selectByMap(map);
        if (lst.size() == 1) {
            result.setData(lst.get(0));
            result.setStatus(Status.SUCCESS);
        } else {
            result.setMsg(i18nUtils.getVal("100004000"));
        }
        session.close();
        return result;
    }

    public ReturnResult audit(int state, String[] idArr) {
        SqlSession session = getSqlSession();
        SysEnumNameDao dao = session.getMapper(SysEnumNameDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("idArr", idArr);
        map.put("state", state);
        Integer num = dao.audit(map);
        ReturnResult result = new ReturnResult();
        if (num > 0) {
            result.setMsg(i18nUtils.getVal("100001000"));
            result.setStatus(Status.SUCCESS);
        }
        setEnumCache();
        session.close();
        return result;
    }

    /**
     * 排序
     *
     * @param sorts
     * @param ids
     * @return
     */
    public ReturnResult sort(String sorts, String ids) {
        ReturnResult result;
        SqlSession session = getSqlSession();
        SysEnumNameDao dao = session.getMapper(SysEnumNameDao.class);
        result = sort(session, dao, sorts, ids);
        if (session != null)
            session.close();
        return result;
    }
}
